from Algorithm import Algorithm
import commands,shutil,sys,os
from postProccesing import postProccesor

class MalibuAlg(Algorithm):
	def __init__(self, name):
		self.name = name
		self.attributes = {}
		self.explain = {}
		
	def doMalibuPars(self):
		failure, res = commands.getstatusoutput(self.name)
		for l in res.split("\n"):
			if(len(l)>0 and not l[0]=='#' and not l[0:28]=='single_classifier::main(194)'):
				t = l.split('#')
				att = t[0].split()
				desc = t[1].replace('#','')
				self.explain[att[0]] = desc
				if(len(att)>1):
					self.attributes[att[0]] = att[1]
				else: 
					self.attributes[att[0]] = ''
		
	def getRun(self):
		return MalAlgRun(self)

class MalAlgRun:
	def __init__(self,alg):
		self.pars = {}
		self.pars.update(alg.attributes.items())
		self.algo = alg
	
	def __str__(self):
		s = self.algo.name + "\n"
		for atr in self.pars.items():
			if(not self.algo.attributes[atr[0]] == atr[1]):
				s += "	" +  str(atr) + "\n"
		return s[:-1] 
	
	# invars is a list of attribute vlaue tuple
	def setValue(self,inVars):
		#print inVars[0]
		for tuple in inVars:
			if self.pars.has_key(tuple[0]):
				self.pars[tuple[0]] = tuple[1]
	
	#run algorithm on machine m	
	def runMe(self,m,dirTo):
		print "---> Running: " + str(self) 
		print 
		print "	Machine: " + str(m)
		outFileCfg =  self.algo.name + "_" + os.path.basename(self.pars['trainfile:'].replace(".dataset","")) + ".cfg"
		outFileRes = outFileCfg.replace(".cfg",".out")
		print "	Output file: ./" + outFileRes
		cFileLocal = self.createConfigFileLocal(dirTo,outFileCfg) # always make local file for later
		outFileRes = dirTo + '/' + outFileRes
		if(m.type == 'local'):
			command =  self.algo.name + '<' +cFileLocal  + '>' + outFileRes
			os.system(command)
		postProccesor(dirTo).malibuProcces()
		print "---> Done with: " + str(self)
	
	#writes out the configFile to directory
	def createConfigFileLocal(self,dirTo,outFileCfg):
		outPath = os.path.dirname(self.pars['trainfile:'])
		print "	Config file: ./" + outFileCfg
		failure, res = commands.getstatusoutput(self.algo.name)
		file = open(dirTo + "/"+ outFileCfg,'w')
		#for l in res.split("\n"):
		for t in res.split('\n')[1:]: #modify lines for which we have pars
			if(len(t.split())>0 and self.pars.has_key(t.split()[0])):
				file.write(t.split()[0] + " " + self.pars[t.split()[0]] + '\n')
			else:
				file.write(t + '\n')
		file.close()
		return dirTo + "/"+ outFileCfg # return location of file
		
		
	